
import 'dart:convert';
import 'dart:io';

import 'package:flutter_test/flutter_test.dart';
import 'package:im_app/im/dao/ImSessionDao.dart';
import 'package:im_app/im/pojo/Enums.dart';
import 'package:im_app/im/pojo/ImPojo.dart';
import 'package:im_app/im/service/ImMessageSendService.dart';
import 'package:im_app/im/service/LoginService.dart';
import 'package:im_app/im/service/ImMessageService.dart';
import 'package:im_app/im/socket/ImWebSocketIsolate.dart';
import 'package:im_app/im/socket/ImWebSocketIsolate2.dart';
import 'package:im_app/im/socket/dto/base/Resp.dart';
import 'package:im_app/im/socket/dto/business/Login.dart';
import 'package:im_app/im/socket/dto/business/Message.dart';
import 'package:im_app/im/util/DbUtil.dart';
import 'package:im_app/im/util/ImSingleton.dart';
import 'package:logger/logger.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';

void main() {
	test("test websocket send message", () async {
		ImWebSocketIsolate imWebSocket = new ImWebSocketIsolate('ws://127.0.0.1:9290/imWebsocket');
		await imWebSocket.start();
		ImSingleton.getInstance()?.imWebSocket = imWebSocket;

		var database = await initSqlite();
		var logger = Logger();
		logger.i("websocket run");

		LoginReq loginReq = LoginReq(userId: "test00100", password: "123456", machineCode: "demo",
				tenantCode: "0000", terminalType: "android");
		logger.i("login json: " + loginReq.toJson().toString());
		LoginService loginService = LoginService();
		LoginResp? loginResp = await loginService.login(loginReq, LoginType.password);
		logger.i("login success result : " + jsonEncode(loginResp));

		var messageSendService = new ImMessageSendService();
		var sessionDao = new ImSessionDao();
		var imSession = await sessionDao.getByUserId("test00100", "test00100", "test00200");
		var imMessage = ImMessage(fromUserId: "test00100", content: "hello word", messageType: ImMessageType.Text);
		imMessage.status = ImMessageStatus.created;
		imSession?.latelyMessage = imMessage.content;
		await messageSendService.sendMessage([imSession!], [imMessage]);
		var duration = const Duration(seconds: 10);
		logger.i('Start sleeping');
		sleep(duration);
		imWebSocket.close();
		database.close();
	}, timeout: Timeout.factor(3));
}

Future<Database> initSqlite() async {
	sqfliteFfiInit();
	databaseFactory = databaseFactoryFfi;
	Database database = await DbUtil.connect("im-test.db");
	return database;
}